# R 语言读取二进制文件

# 将mtcars 读取为csv文件 然后将其二进制写入系统
setwd("G:/R_learn/R_learn03")

write.table(mtcars,file="mtcars.csv",row.names = FALSE,na="",col.names = TRUE,sep=",")

# 读取五条记录
new.mtcars <- read.table("mtcars.csv",sep=",",header=TRUE,nrows=5);

#创建保存二进制文件路径
write.filename <- file("binmtcars.dat","wb");

# 以二进制文件写入 其中一列
writeBin(colnames(new.mtcars),write.filename);

writeBin(c(new.mtcars$cyl,new.mtcars$am,new.mtcars$gear),write.filename)

close( write.filename )

# 读取二进制文件
read.filename <- file("binmtcars.dat","rb");

# 读取每列的名字 n =3( 有三列数据)
column.names <- readBin(read.filename,character(),n=3);
print( column.names );


bindata <- readBin(read.filename,integer(),n=18)

print( bindata );

cyldata <- bindata[4:8];

print( cyldata )

amdata <- bindata[9:13];
print( amdata );

geardata <- bindata[14:18];
print( geardata );

mergedata <- cbind(cyldata,amdata,geardata);
colnames(mergedata) = column.names
print( mergedata )
